package org.chen.ctrip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.ctrip.dto.ProductMultilangRequest;
import org.chen.common.ctrip.entity.Product;
import org.chen.common.ctrip.entity.ProductMultilang;
import org.chen.common.scene.entity.District;
import org.chen.ctrip.mapper.ProductMapper;
import org.chen.ctrip.mapper.ProductMultilangMapper;
import org.chen.ctrip.service.ProductMultilangService;
import org.chen.ctrip.service.ProductService;
import org.chen.ctrip.service.translate.markdown.HtmlToMarkdownService;
import org.chen.ctrip.service.translate.service.BaiduTranslationService;
import org.chen.ctrip.service.translate.service.ContentTranslationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class ProductMultilangServiceImpl extends ServiceImpl<ProductMultilangMapper, ProductMultilang> implements ProductMultilangService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductMultilangMapper productMultilangMapper;

    @Autowired
    private HtmlToMarkdownService htmlToMarkdownService;

    @Autowired
    private ContentTranslationService contentTranslationService;

    private static final String DEFAULT_LANGUAGE = "zh";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private BaiduTranslationService baiduTranslationService;

    /**
     * 获取产品的多语言内容
     */
    public ProductMultilang getProductMultilangContent(String productId, String languageCode) {
        // 如果是中文，直接返回原始数据（转换为markdown）
        if (DEFAULT_LANGUAGE.equals(languageCode)) {
            return getOrCreateDefaultLanguageContent(productId);
        }

        // 查找目标语言的现有数据
        ProductMultilang existingMultilang = productMultilangMapper.selectByProductIdAndLanguage(productId, languageCode);
        if (existingMultilang != null) {
            log.info("找到现有多语言内容，产品ID: {}, 语言: {}", productId, languageCode);
            return existingMultilang;
        }

        // 如果不存在，则创建新的多语言内容
        return createMultilangContent(productId, languageCode);
    }

    /**
     * 获取或创建默认语言（中文）内容
     */
    private ProductMultilang getOrCreateDefaultLanguageContent(String productId) {
        ProductMultilang defaultContent = productMultilangMapper.selectByProductIdAndLanguage(productId, DEFAULT_LANGUAGE);

        if (defaultContent != null && StringUtils.hasText(defaultContent.getPageContentMarkdown())) {
            return defaultContent;
        }

        // 如果不存在或内容为空，则从原表获取并转换
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("产品不存在: " + productId);
        }

        String markdownContent = "";
        if (StringUtils.hasText(product.getPageDiv())) {
            try {
                // 🔥 使用优化的处理流程：HTML转换 + Ollama总结
                log.info("开始处理产品{}的HTML内容，长度: {}", productId, product.getPageDiv().length());

                // 1. HTML转换为按天分割的Markdown
                List<String> dayMarkdowns = htmlToMarkdownService.convertHtmlToMarkdownByDay(product.getPageDiv());
                log.info("HTML转换完成，分割为{}天", dayMarkdowns.size());

                if (!dayMarkdowns.isEmpty()) {
                    // 2. 使用Ollama对每天的内容进行总结
                    List<String> summarizedDays = contentTranslationService.summarizeDayContents(dayMarkdowns);

                    // 3. 合并所有天的内容
                    markdownContent = contentTranslationService.mergeDayContents(summarizedDays);

                    // 4. 打印处理统计
                    ContentTranslationService.ProcessingStats stats =
                            contentTranslationService.getProcessingStats(dayMarkdowns, summarizedDays);
                    log.info("内容处理完成: {}", stats);
                }

            } catch (Exception e) {
                log.error("优化处理失败，使用备用方案，产品ID: {}", productId, e);
                // 备用方案：使用传统的转换方法
                markdownContent = htmlToMarkdownService.convertHtmlTableToMarkdown(product.getPageDiv());
            }
        }

        // 保存或更新默认语言内容
        if (defaultContent == null) {
            defaultContent = new ProductMultilang();
            defaultContent.setProductId(productId);
            defaultContent.setLanguageCode(DEFAULT_LANGUAGE);
            defaultContent.setPageContentMarkdown(markdownContent);
            defaultContent.setTranslatedContent(markdownContent); // 默认语言不需要翻译
            defaultContent.setCreateTime(LocalDateTime.now());
            defaultContent.setUpdateTime(LocalDateTime.now());
            productMultilangMapper.insert(defaultContent);
            log.info("保存默认语言内容，产品ID: {}, 内容长度: {}", productId, markdownContent.length());
        } else {
            defaultContent.setPageContentMarkdown(markdownContent);
            defaultContent.setTranslatedContent(markdownContent);
            defaultContent.setUpdateTime(LocalDateTime.now());
            productMultilangMapper.updateById(defaultContent);
            log.info("更新默认语言内容，产品ID: {}, 内容长度: {}", productId, markdownContent.length());
        }

        return defaultContent;
    }

    /**
     * 创建多语言内容 - 使用Ollama总结 + 百度翻译
     */
    @Transactional
    public ProductMultilang createMultilangContent(String productId, String languageCode) {
        log.info("开始创建多语言内容，产品ID: {}, 目标语言: {}", productId, languageCode);

        // 1. 确保默认语言内容存在
        ProductMultilang defaultContent = getOrCreateDefaultLanguageContent(productId);

        if (!StringUtils.hasText(defaultContent.getPageContentMarkdown())) {
            throw new RuntimeException("默认语言内容为空，无法翻译");
        }

        try {
            // 🔥 翻译流程：分天处理 + 百度翻译
            String translatedContent = translateContentWithBaiduApi(defaultContent.getPageContentMarkdown(), languageCode);

            // 3. 保存翻译结果
            ProductMultilang multilangContent = new ProductMultilang();
            multilangContent.setProductId(productId);
            multilangContent.setLanguageCode(languageCode);
            multilangContent.setPageContentMarkdown(defaultContent.getPageContentMarkdown());
            multilangContent.setTranslatedContent(translatedContent);
            multilangContent.setCreateTime(LocalDateTime.now());
            multilangContent.setUpdateTime(LocalDateTime.now());

            productMultilangMapper.insert(multilangContent);

            log.info("多语言内容创建成功，产品ID: {}, 语言: {}, 原文长度: {}, 译文长度: {}",
                    productId, languageCode,
                    defaultContent.getPageContentMarkdown().length(),
                    translatedContent.length());
            return multilangContent;

        } catch (Exception e) {
            log.error("创建多语言内容失败，产品ID: {}, 语言: {}", productId, languageCode, e);
            throw new RuntimeException("翻译失败: " + e.getMessage());
        }
    }

    /**
     * 🔥 使用百度翻译API进行内容翻译
     */
    private String translateContentWithBaiduApi(String markdownContent, String targetLanguage) {
        try {
            // 按分隔符分割成天
            String[] dayContents = markdownContent.split("\n\n---\n\n");

            // 转换为List进行处理
            List<String> dayList = List.of(dayContents);

            // 使用百度翻译API翻译每天的内容
            List<String> translatedDays = contentTranslationService.translateDayContentsByBaidu(dayList, targetLanguage);

            // 合并翻译结果
            return contentTranslationService.mergeDayContents(translatedDays);

        } catch (Exception e) {
            log.error("百度翻译失败: {}", e.getMessage());
            throw new RuntimeException("百度翻译失败: " + e.getMessage());
        }
    }

    /**
     * 强制刷新某个产品的多语言内容
     */
    @Transactional
    public void refreshMultilangContent(String productId, String languageCode) {
        log.info("强制刷新多语言内容，产品ID: {}, 语言: {}", productId, languageCode);

        // 删除现有内容
        productMultilangMapper.deleteByProductIdAndLanguage(productId, languageCode);

        // 重新创建
        createMultilangContent(productId, languageCode);
    }

    @Override
    public void saveMultilang(ProductMultilangRequest multilang) {
        Product product = productMapper.selectById(multilang.getProductId());

        if (product == null) {
            throw new RuntimeException("产品不存在: " + multilang.getProductId());
        }

        ProductMultilang getMultilang = productMultilangMapper.selectOne(new QueryWrapper<ProductMultilang>().eq("product_id", multilang.getProductId()).eq("language_code", multilang.getLanguageCode()));

        if (getMultilang == null) {
            ProductMultilang productMultilang = new ProductMultilang();
            productMultilang.setProductId(multilang.getProductId());
            productMultilang.setLanguageCode(multilang.getLanguageCode());
            productMultilang.setTranslatedContent(multilang.getTranslatedContent());
            productMultilang.setPageContentMarkdown(multilang.getPageContentMarkdown());
            productMultilang.setCreateTime(LocalDateTime.now());

            saveProductMultilangSafely(productMultilang, product);
        } else {
            getMultilang.setLanguageCode(multilang.getLanguageCode());
            getMultilang.setTranslatedContent(multilang.getTranslatedContent());
            getMultilang.setPageContentMarkdown(multilang.getPageContentMarkdown());
            getMultilang.setUpdateTime(LocalDateTime.now());

            productMultilangMapper.updateById(getMultilang);
        }
    }

    private void saveProductMultilangSafely(ProductMultilang productMultilang, Product product) {
        String lockKey = "productMultilang_lock:" + productMultilang.getProductId();
        String lockValue = UUID.randomUUID().toString();

        try {
            // 尝试获取锁
            Boolean lockAcquired = redisTemplate.opsForValue()
                    .setIfAbsent(lockKey, lockValue, Duration.ofSeconds(10));

            if (Boolean.TRUE.equals(lockAcquired)) {
                // 再次检查是否存在
                ProductMultilang existing = productMultilangMapper.selectOne(
                        new QueryWrapper<ProductMultilang>().eq("product_id", productMultilang.getProductId())
                                .eq("language_code", productMultilang.getLanguageCode()));

                if (existing == null) {

                    String translated = baiduTranslationService.translate(product.getTitle(), "zh", productMultilang.getLanguageCode());

                    productMultilang.setTitle(translated);

                    productMultilangMapper.insert(productMultilang);
                } else {
                    log.info("多语言内容已存在，产品ID: {}, 语言: {}", productMultilang.getProductId(), productMultilang.getLanguageCode());
                    throw new RuntimeException("多语言内容已存在: " + productMultilang.getProductId());
                }
            }
        } catch (Exception e) {
            // 释放锁
            String currentValue = redisTemplate.opsForValue().get(lockKey);
            if (lockValue.equals(currentValue)) {
                redisTemplate.delete(lockKey);
            }
        }
    }
}